// src/api/orders.js
// 订单相关API

/**
 * 获取用户订单列表
 * @param {string} userId - 用户ID
 * @returns {Promise} 订单列表
 */
export async function getOrders(userId) {
  // 模拟API调用
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        data: [
          {
            id: 'ORD20241215001',
            userId: userId,
            scenicSpotName: '三坊七巷',
            scenicSpotId: 'spot001',
            visitDate: '2024-12-20',
            visitTime: '09:00-12:00',
            visitorCount: 2,
            visitorName: '张三',
            visitorPhone: '13800138000',
            visitorIdCard: '350102199001011234',
            ticketType: '成人票',
            unitPrice: 60,
            totalAmount: 120,
            status: 'paid',
            paymentTime: '2024-12-15 10:30:00',
            createTime: '2024-12-15 10:25:00'
          },
          {
            id: 'ORD20241215002',
            userId: userId,
            scenicSpotName: '鼓山',
            scenicSpotId: 'spot002',
            visitDate: '2024-12-22',
            visitTime: '13:00-16:00',
            visitorCount: 1,
            visitorName: '张三',
            visitorPhone: '13800138000',
            visitorIdCard: '350102199001011234',
            ticketType: '学生票',
            unitPrice: 40,
            totalAmount: 40,
            status: 'pending',
            createTime: '2024-12-15 14:20:00'
          }
        ],
        total: 2,
        page: 1,
        pageSize: 10
      })
    }, 500)
  })
}

/**
 * 获取订单详情
 * @param {string} orderId - 订单ID
 * @returns {Promise} 订单详情
 */
export async function getOrderDetail(orderId) {
  return new Promise((resolve) => {
    setTimeout(() => {
      const orders = {
        'ORD20241215001': {
          id: 'ORD20241215001',
          userId: 'user123',
          scenicSpotName: '三坊七巷',
          scenicSpotId: 'spot001',
          scenicSpotAddress: '福州市鼓楼区南后街',
          visitDate: '2024-12-20',
          visitTime: '09:00-12:00',
          visitorCount: 2,
          visitors: [
            {
              name: '张三',
              phone: '13800138000',
              idCard: '350102199001011234',
              ticketType: '成人票'
            },
            {
              name: '李四',
              phone: '13800138001',
              idCard: '350102199002022345',
              ticketType: '成人票'
            }
          ],
          ticketType: '成人票',
          unitPrice: 60,
          totalAmount: 120,
          status: 'paid',
          paymentMethod: '微信支付',
          paymentTime: '2024-12-15 10:30:00',
          createTime: '2024-12-15 10:25:00',
          qrCode: 'https://example.com/qr/ORD20241215001'
        },
        'ORD20241215002': {
          id: 'ORD20241215002',
          userId: 'user123',
          scenicSpotName: '鼓山',
          scenicSpotId: 'spot002',
          scenicSpotAddress: '福州市晋安区鼓山镇',
          visitDate: '2024-12-22',
          visitTime: '13:00-16:00',
          visitorCount: 1,
          visitors: [
            {
              name: '张三',
              phone: '13800138000',
              idCard: '350102199001011234',
              ticketType: '学生票'
            }
          ],
          ticketType: '学生票',
          unitPrice: 40,
          totalAmount: 40,
          status: 'pending',
          createTime: '2024-12-15 14:20:00'
        }
      }
      resolve({ data: orders[orderId] || null })
    }, 300)
  })
}

/**
 * 创建新订单
 * @param {Object} orderData - 订单数据
 * @returns {Promise} 创建结果
 */
export async function createOrder(orderData) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        data: {
          id: `ORD${Date.now()}`,
          ...orderData,
          status: 'pending',
          createTime: new Date().toISOString()
        },
        success: true,
        message: '订单创建成功'
      })
    }, 500)
  })
}

/**
 * 取消订单
 * @param {string} orderId - 订单ID
 * @returns {Promise} 取消结果
 */
export async function cancelOrder(orderId) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        success: true,
        message: '订单取消成功'
      })
    }, 300)
  })
}

/**
 * 支付订单
 * @param {string} orderId - 订单ID
 * @param {string} paymentMethod - 支付方式
 * @returns {Promise} 支付结果
 */
export async function payOrder(orderId, paymentMethod) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        success: true,
        message: '支付成功',
        data: {
          paymentTime: new Date().toISOString(),
          paymentMethod: paymentMethod
        }
      })
    }, 800)
  })
}

/**
 * 获取订单状态统计
 * @param {string} userId - 用户ID
 * @returns {Promise} 状态统计
 */
export async function getOrderStats(userId) {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({
        data: {
          total: 15,
          paid: 8,
          pending: 3,
          cancelled: 4
        }
      })
    }, 200)
  })
}

/**
 * 创建订单并发起支付
 * @param {Object} orderData - 订单数据，包含orderInfo和touristList
 * @returns {Promise} 创建和支付结果
 */
export async function createOrderWithPayment(orderData) {
  try {
    // 真实的API调用
    const response = await fetch('/api/admin/scenicOrder/createOrderWithPayment', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        // 如果需要认证，可以添加Authorization头
        // 'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify(orderData)
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const text = await response.text();
    if (!text) {
      throw new Error('服务器返回空响应');
    }

    let result;
    try {
      result = JSON.parse(text);
    } catch (parseError) {
      console.error('JSON解析失败:', text);
      throw new Error('服务器返回的数据格式不正确');
    }

    if (result.code === 200 || result.success) {
      return result;
    } else {
      throw new Error(result.msg || '创建订单并支付失败');
    }
  } catch (error) {
    console.error('创建订单并支付失败:', error);
    throw error;
  }
}